package com.jy.rhin.parse;

import com.jy.rhin.infra.cda.XPath;
import com.jy.rhin.infra.cda.util.ReflectUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.nodes.Element;
import org.seimicrawler.xpath.JXNode;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
 * @Author 姚俊
 * @Date 2023/2/14 17:42
 * @Description 解析器基类
 */
@Slf4j
public class CDAParseSupport {

    public static void setAllFieldValues(JXNode root, Object dataModel) throws InstantiationException, IllegalAccessException {
        for (Field field : ReflectUtils.getAllFields(dataModel.getClass())) {
            Class<?> type = field.getType();
            XPath xPath = field.getAnnotation(XPath.class);
            if (Objects.isNull(xPath)) {
                log.warn("类型:{}没有@XPath注解，无法解析", field.getType());
                continue;
            }
            Selector selector = ParserFactory.getParser(xPath);
            if (isSimpleType(type)) {
                String value = selector.selectValue(root, xPath);
                setFieldValue(dataModel, value, field);
            } else if (!type.equals(List.class)) {
                JXNode jxNode = root.selOne(xPath.path());
                if (Objects.isNull(jxNode)) {
                    //log.debug("当前文档不存在该节点{}", xPath.path());
                    continue;
                }
                Object childDataModel = createDataModel(type);
                setAllFieldValues(jxNode, childDataModel);
                setFieldValue(dataModel, childDataModel, field);
            } else {
                try {
                    //获取list泛型类型
                    Class<?> rawClass = ReflectUtils.getListRawClass(field);
                    if (Objects.isNull(rawClass)) {
                        log.error("list未指定泛型，无法处理");
                        continue;
                    }
                    JXNode jxNode = root.selOne(xPath.path());
                    String listItemPath = xPath.listItemPath();
                    if (StringUtils.isEmpty(listItemPath)) {
                        log.error("字段{}为list属性,请配置listItemPath分隔文档", field.getName());
                        continue;
                    }
                    if (jxNode == null) {
                        continue;
                    }
                    List<JXNode> itemNodes = jxNode.sel(listItemPath);
                    ArrayList<JXNode> nodes = new ArrayList<>(itemNodes.size());
                    for (JXNode itemNode : itemNodes) {
                        Element element = itemNode.asElement();
                        for (int i = 0; i < xPath.listItemBackLevel(); i++) {
                            element = element.parent();
                        }
                        nodes.add(new JXNode(element));
                    }
                    if (CollectionUtils.isEmpty(nodes)) {
                        //log.debug("当前文档不存在该节点{}", xPath.path());
                        continue;
                    }
                    List<Object> curEleList = new ArrayList<>(nodes.size());
                    boolean isSimpleEle = isSimpleType(rawClass);
                    for (JXNode node : nodes) {
                        Object eleDataModel;
                        if (isSimpleEle) {
                            eleDataModel = selector.selectValue(node, xPath);
                        } else {
                            eleDataModel = createDataModel(rawClass);
                            setAllFieldValues(node, eleDataModel);
                        }
                        if (Objects.nonNull(eleDataModel)) {
                            curEleList.add(eleDataModel);
                        } else {
                            log.debug("当前节点文档{}无法解析出对应的数据", node);
                        }
                    }
                    setFieldValue(dataModel, curEleList, field);
                } catch (Exception e) {
                    log.error("处理list字段失败", e);
                }
            }
        }
    }

    private static void setFieldValue(Object obj, Object value, Field field) {
        try {
            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), obj.getClass());
            Method writeMethod = pd.getWriteMethod();
            writeMethod.invoke(obj, value);
        } catch (IntrospectionException | InvocationTargetException | IllegalAccessException |
                 IllegalArgumentException e) {
//            log.error("属性设置错误", e);
            log.error(String.format("属性设置错误%s, %s, %s", obj.getClass(), value, field.getName()), e);
        }
    }

    private static boolean isSimpleType(Class<?> clazz) {
        return BeanUtils.isSimpleValueType(clazz);
    }

    private static <T> T createDataModel(Class<T> clazz) throws InstantiationException, IllegalAccessException {
        return clazz.newInstance();
    }
}
